/**
 * 相册服务器版
 * 1. 添加图片功能, 应把图片上传到服务器上
 * 2. 所有相册信息, 比如分类信息等等要保存到服务器端, 这样可以保证, 重新刷新浏览器, 也有数据。
 * 3. 增删图片时, 也会增删服务器端的图片文件.
 */
const path = require("path");
const fs = require("fs-extra");
const multer = require("multer");

const readFile = require("../data");

let configRoutesMethod = (app) => {
    app.get("/", (req, res) => {
        readFile("./public/img").then(result => {
            // console.log(result);
            res.render("layout", {albumList: result});
            // res.render("layout", {});
        });
    });

    app.get("/index", (req, res) => {
        res.redirect("/homepage.html");
    });

    app.post("/upload-album", (req, res) => {
        let albumName = req.body.albumName;
        fs.mkdir(path.join(__dirname, `../public/img/${albumName}`), function (error) {
            if (error) {
                console.error(error);
            } else {
                console.log("Successfully make a directory " + albumName);
            }
        });
        res.send();
    });

    app.delete("/delete-album/:name", (req, res) => {
        let albumName = req.params.name;
        fs.remove(path.join(__dirname, `../public/img/${albumName}`), function (err) {
            if (err) {
                console.error(err);
            } else{
                console.log("Successfully remove a directory." + albumName);
            }
        });
        res.send();
    });

    let defaultUrl = path.join(__dirname, "../public/img/默认相册");
    var upload = multer({
        dest: defaultUrl
    });

    app.post("/upload-pic/:name", upload.single("myFile"), (req, res) => {
        let albumName = req.params.name;
        console.log(albumName);
        if (albumName !== "默认相册") {
            fs.move(req.file.path, path.join(__dirname, `../public/img/${albumName}/${req.file.filename}`), function(err) {
                if (err) return console.error(err);
            });
        }
        console.log("Successfully upload the pic to " + req.params.name);
        // console.log(req.file);
        res.send(req.file);
    });

    app.delete("/delete-pic", (req, res) => {
        let albumName = req.query.albumName;
        let filename = req.query.filename;
        fs.remove(path.join(__dirname, `../public/img/${albumName}/${filename}`), function (err) {
            if (err) {
                console.error(err);
            } else{
                console.log("Successfully remove a file ");
            }
        });
        res.send();
    });
}

module.exports = configRoutesMethod;

